package org.java.http;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.PropertyConfigurator;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * java 调用http接口 Hello World
 * Created by Dwyane-Wevil on 2017/1/1.
 */
public class QuickStart {

    private static String config = System.getProperty("user.dir") + "\\src\\resource\\log4j.properties";

    static {
        PropertyConfigurator.configure(config);
    }

    public static void main(String[] args) throws Exception {
        // 测试http get 请求
        //testGet();
        // 测试http post 请求
        testPost();
    }

    /**
     * 测试http get 请求
     */
    public static void testGet() throws Exception {

        CloseableHttpClient httpclient = HttpClients.createDefault();

        try {
            // 请求地址
            //HttpGet httpGet = new HttpGet("http://httpbin.org/get");
            HttpGet httpGet = new HttpGet("https://www.baidu.com");
            // 执行get请求
            CloseableHttpResponse response1 = httpclient.execute(httpGet);
            try {
                // 获取返回的状态
                System.out.println(response1.getStatusLine());
                HttpEntity entity1 = response1.getEntity();

                // 获取返回的内容
                System.out.println(convertStreamToString(entity1.getContent()));

                // 销毁entity
                EntityUtils.consume(entity1);
            } finally {
                response1.close();
            }
        } finally {
            httpclient.close();
        }
    }

    /**
     * 测试http post 请求
     */
    public static void testPost() throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();

        try {
            // 请求地址
            HttpPost httpPost = new HttpPost("http://httpbin.org/post");
            //HttpPost httpPost = new HttpPost("https://www.baidu.com");

            // 添加请求参数
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("username", "vip"));
            nvps.add(new BasicNameValuePair("password", "secret"));
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));

            // 执行Post请求
            CloseableHttpResponse response2 = httpclient.execute(httpPost);
            try {
                System.out.println(response2.getStatusLine());
                HttpEntity entity2 = response2.getEntity();

                // 获取返回的内容
                System.out.println(convertStreamToString(entity2.getContent()));

                EntityUtils.consume(entity2);
            } finally {
                response2.close();
            }
        } finally {
            httpclient.close();
        }
    }

    /**
     * InputStream 转 String
     *
     * @param is 输入流 InputStream
     */
    public static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}
